package com.newbee.fragement.reg;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.SlidingDrawer;
import android.widget.TextView;
import android.widget.Toast;

import com.hhu.newbee.R;
import com.newbee.activity.regist.RegisterActivity;
import com.newbee.app.OnRefrushActivity;
import com.newbee.round.CustomImageView;
import com.newbee.service.MainService;
import com.newbee.service.MainServiceKey;
import com.newbee.service.MainServiceTask;
import com.newbee.service.TaskType;
import com.newbee.util.MD5Util;

public class RegInfoFragement extends Fragment implements OnClickListener,
		OnRefrushActivity

{
	private static final int GET_FROM_CAMERA = 1001;
	private static final int GET_FROM_PHOTO = 1002;
	private static final int GET_CROP = 1003;
	private TextView nackName;
	private TextView password;
	private TextView passwordRepeat;
	private ProgressDialog progressDialog;
	// private GridView gv;
	private SlidingDrawer sd;
	private ImageView iv;

	private CustomImageView mRegHead;

	// private List<Integer> headList = Arrays.asList(R.drawable.h1,
	// R.drawable.h2, R.drawable.h3, R.drawable.h4, R.drawable.h5,
	// R.drawable.h6, R.drawable.h7, R.drawable.h8, R.drawable.h9,
	// R.drawable.h10, R.drawable.h11, R.drawable.h12);

	// private int headnumb;// 该字段已经废除了

	private String headFileName;

	private static final String CAMERA_HEAD_TEMP = "/newbeeheadtemp";

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState)
	{

		View view = inflater.inflate(R.layout.fragement_reg_info, container,
				false);
		view.findViewById(R.id.reg_info_btn_back).setOnClickListener(this);
		view.findViewById(R.id.regInfoNextbtn).setOnClickListener(this);
		this.nackName = (TextView) view.findViewById(R.id.regInfoNick);
		this.password = (TextView) view.findViewById(R.id.regInfoPwd);
		this.passwordRepeat = (TextView) view
				.findViewById(R.id.regInfoPwdRepeat);

		File file = new File(Environment.getExternalStorageDirectory()
				+ CAMERA_HEAD_TEMP);
		if (!file.exists())
		{
			file.mkdirs();
		}

		progressDialog = new ProgressDialog(this.getActivity());
		progressDialog.setCancelable(false);
		progressDialog.setMessage("正在注册，请稍等……");

		sd = (SlidingDrawer) view.findViewById(R.id.sliding);
		iv = (ImageView) view.findViewById(R.id.imagedir);

		view.findViewById(R.id.select_head_camera).setOnClickListener(this);
		view.findViewById(R.id.select_head_photo).setOnClickListener(this);

		mRegHead = (CustomImageView) view.findViewById(R.id.reg_head);
		mRegHead.setOnClickListener(this);
		sd.setOnDrawerOpenListener(new SlidingDrawer.OnDrawerOpenListener()// 开抽屉
		{
			@Override
			public void onDrawerOpened()
			{
				iv.setImageResource(R.drawable.down);// 响应开抽屉事件

			}
		});
		sd.setOnDrawerCloseListener(new SlidingDrawer.OnDrawerCloseListener()
		{
			@Override
			public void onDrawerClosed()
			{
				iv.setImageResource(R.drawable.up);// 响应关抽屉事件
			}
		});

		return view;
	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{

		case R.id.regInfoNextbtn:
		{

			if (this.nackName.getText().toString().length() == 0)
			{
				Toast.makeText(this.getActivity(), "昵称不能为空", Toast.LENGTH_LONG)
						.show();
				return;
			}
			if (this.password.getText().toString().length() == 0)
			{
				Toast.makeText(this.getActivity(), "密码不能为空", Toast.LENGTH_LONG)
						.show();
				return;
			}
			if (this.passwordRepeat.getText().toString().length() == 0)
			{
				Toast.makeText(this.getActivity(), "重复密码不能为空",
						Toast.LENGTH_LONG).show();
				return;
			}
			if (this.passwordRepeat.getText().toString()
					.equals(this.password.getText().toString()))
			{

				// 发送消息进行注册
				Map<String, Object> paras = new HashMap<String, Object>();
				RegisterActivity ra = (RegisterActivity) this.getActivity();

				paras.put(MainServiceKey.EMAIL, ra.getEmail());

				paras.put(MainServiceKey.PASSWORD, this.password.getText()
						.toString());
				paras.put(MainServiceKey.NICK_NAME,
						MD5Util.MD5Encrypt(this.nackName.getText().toString())
								.subSequence(0, 5));

				paras.put(MainServiceKey.USERNAME, this.nackName.getText()
						.toString());

				paras.put(MainServiceKey.HEAD_FILE_NAME, headFileName);

				MainServiceTask mst = new MainServiceTask(TaskType.USER_REGIST,
						paras, RegInfoFragement.class.getName());
				MainService.addActivityMap(RegInfoFragement.class.getName(),
						this);
				MainService.addTaskQueue(mst);

			}
			else
			{
				Toast.makeText(this.getActivity(), "密码和重复密码必须一致",
						Toast.LENGTH_LONG).show();
			}

			break;

		}
		case R.id.reg_info_btn_back:
		{

			RegisterActivity ra = (RegisterActivity) this.getActivity();
			ra.goToNextPager(0);

			break;
		}
		case R.id.reg_head:
		{
			sd.animateOpen();
			break;
		}
		case R.id.select_head_camera:
		{
			Intent intentPhote = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			intentPhote.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
			File out = new File(Environment.getExternalStorageDirectory()
					+ CAMERA_HEAD_TEMP + "/temphead.png");
			Uri uri = Uri.fromFile(out);
			// 获取拍照后未压缩的原图片，并保存在uri路径中
			intentPhote.putExtra(MediaStore.EXTRA_OUTPUT, uri);
			startActivityForResult(intentPhote, GET_FROM_CAMERA);
			sd.animateClose();
			break;
		}
		case R.id.select_head_photo:
		{
			Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
			intent.setType("image/*");
			startActivityForResult(intent, GET_FROM_PHOTO);
			sd.animateClose();
			break;
		}
		default:
			break;
		}

	}

	@Override
	public void onDestroy()
	{
		progressDialog.dismiss();
		super.onDestroy();
	}

	@Override
	public void init()
	{
		// TODO Auto-generated method stub

	}

	@Override
	public RtInfo refresh(int taskID, Object... paras)
	{

		switch (taskID)
		{
		case TaskType.USER_REGIST:
		{

			boolean re = (Boolean) paras[0];

			if (re)
			{
				RegisterActivity ra = (RegisterActivity) this.getActivity();
				ra.goToNextPager(2);

			}

			break;
		}
		default:
			break;
		}

		return null;
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == GET_FROM_CAMERA)
		{

			try
			{
				Bitmap bm = BitmapFactory.decodeStream(new FileInputStream(
						new File(Environment.getExternalStorageDirectory()
								+ CAMERA_HEAD_TEMP + "/temphead.png")));
				Uri uri = saveBitmap(bm);
				startimageZoon(uri);
			}
			catch (Exception e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		else if (requestCode == GET_FROM_PHOTO)
		{

			if (data != null)
			{
				Uri uri = data.getData();
				try
				{
					uri = converUri(uri);
					startimageZoon(uri);
				}
				catch (Exception e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}
		else if (requestCode == GET_CROP)
		{

			if (data != null)
			{

				Bundle bundle = data.getExtras();
				Bitmap bitmap = bundle.getParcelable("data");
				mRegHead.setmSrc(bitmap);

				mRegHead.invalidate();
				RegisterActivity ra = (RegisterActivity) this.getActivity();
				headFileName = "img_" + MD5Util.imgHead(ra.getEmail()) + ".png";
				try
				{
					FileOutputStream fos = new FileOutputStream(
							Environment.getExternalStorageDirectory() + "/"
									+ headFileName);
					bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
					fos.flush();
					fos.close();
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
			}

		}
	}

	private Uri saveBitmap(Bitmap bitmap) throws Exception
	{

		File dir = new File(Environment.getExternalStorageDirectory()
				+ "/headtemp");
		if (!dir.exists())
		{
			dir.mkdir();
		}
		File img = new File(dir.getAbsolutePath() + "/avater.png");
		FileOutputStream fos = new FileOutputStream(img);

		bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
		fos.flush();
		fos.close();
		return Uri.fromFile(img);
	}

	private Uri converUri(Uri uri) throws Exception
	{
		InputStream is = this.getActivity().getContentResolver()
				.openInputStream(uri);
		Bitmap bitmap = BitmapFactory.decodeStream(is);
		is.close();
		return saveBitmap(bitmap);

	}

	private void startimageZoon(Uri uri)
	{
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");

		intent.putExtra("crop", true);
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 150);
		intent.putExtra("outputY", 150);
		intent.putExtra("return-data", true);

		startActivityForResult(intent, GET_CROP);
	}
}
